import os
import json
import folder_dialog as fd
import get_json as gj
import requests
import base64
import uuid
import subprocess
import shutil

settings = {
    # 需要解析的目录
    "dir": "/",
    # 是否读取文件内容
    "read": True,
    # 是否仅获取文件名
    "filename_only": True,
    # 需要获取的文件类型（正则）
    "ext": "\\.(json)$",
}


# settings["dir"] = os.path.realpath(r'C:\Users\haha\Documents\WorldList\export')
# sendmsg = json.dumps(gj.get_json(settings))


def getAud(url, args):
    # 获取网页内容
    response = requests.request("GET", url, params=args)

    # 获取文件的MIME类型
    mime_type = response.headers.get("Content-Type")

    # 将文件编码为base64
    base64_data = base64.b64encode(response.content)
    base64_string = "data:{};base64,{}".format(mime_type, base64_data.decode("utf-8"))

    return base64_string


def baidu_aud(lang, text):
    bast_url = "https://fanyi.baidu.com/gettts"
    args = {"lan": lang, "text": "fox", "spd": "3", "source": "wise", "text": text}
    return getAud(bast_url, args)


# arr = [
#     'https://fanyi.baidu.com/gettts?lan=en&spd=3&source=web&text=Hello',
#     'https://fanyi.baidu.com/gettts?lan=uk&spd=3&source=web&text=Hello'
# ]
# urlToBase64(arr[0])
# urlToBase64(arr[1])
def baidu_translate(text):
    url = "https://fanyi.baidu.com/transapi"
    headers = {"content-type": "application/json"}
    payload = {"from": "en", "to": "zh", "query": text, "source": "txt"}

    response = requests.post(url, headers=headers, data=json.dumps(payload))
    data = response.json()

    return data if not data.get("result") else json.loads(data["result"])


# path = 'E:\\Project\\Repositories\\cpp\\cpp\\httpserver\\py\\export'
# settings["dir"] = os.path.realpath(path)

# with open('./1.json', 'w') as file:
#     file.write(gj.get_json(settings))


def handle_ws_msg(jsonStr, config):
    sendmsg = ""
    code = 0

    # typora路径
    mdEditor_path = os.path.abspath(
        os.path.join(config["dir_root"], "typora/Typora.exe")
    )
    temp_path = f'{os.path.abspath(os.path.join(config["dir_root"], "typora/temp"))}'

    if "typora_path" in config:
        mdEditor_path = os.path.abspath(config["typora_path"])
        temp_path = f'{os.path.dirname(mdEditor_path) + "/temp"}'

    try:
        data = json.loads(jsonStr)
        match data["req"]:
            case "handshake":
                sendmsg = "ok"
            case "setting":
                gsf = 'config/global_settings.json'
                gsp = os.path.abspath(os.path.join(config['dir_root'], gsf))
                match (data['type']):
                    case 'read':
                        if os.path.exists(gsp):
                            with open(gsp, 'r', encoding='utf-8') as f:
                                sendmsg = f.read()
                        else:
                            sendmsg = "文件不存在"
                            code = 404
                    case 'save':
                        dir = os.path.dirname(gsp)
                        try:
                            if not os.path.exists(dir):
                                os.makedirs(dir)
                            with open(gsp, 'w', encoding='utf-8') as f:
                                f.write(data['data'])
                                sendmsg = 'ok'
                        except:
                            sendmsg = '保存失败'
                            code = 1
                    case 'path':
                        sendmsg = gsp
                        
                        
            case "folder_dialog":
                if "folder" in data["type"]:
                    selected_folder = fd.open_folder_dialog()
                    sendmsg = selected_folder
            case "selet_single_exe":
                sendmsg = fd.select_single_exe()

                if "filename" in data:
                    if not sendmsg.endswith(data["filename"] + ".exe"):
                        code = 1
            case "path":
                p_path = data["path"]
                match data["type"]:
                    case "abs":
                        # 转为相对于执行文件的绝对路径
                        sendmsg = os.path.abspath(p_path)
                    case "go":
                        # 跳转到文件夹
                        if not os.path.exists(p_path):
                            os.makedirs(p_path)
                        os.startfile(p_path)
                    case "del":
                        # 删除文件夹
                        if os.path.exists(p_path):
                            shutil.rmtree(p_path)
            case "file":
                p_path = data["path"]
                match data["type"]:
                    case "jsons":
                        settings["dir"] = os.path.realpath(p_path)
                        sendmsg = json.dumps(gj.get_json(settings))
                    case "del":
                        if os.path.exists(p_path):
                            os.remove(p_path)
                    case "go":
                        if os.path.exists(p_path):
                            os.system(f'start explorer /select, "{p_path}"')
            case "save":
                par_path = os.path.realpath(os.path.dirname(data["path"]))
                if not os.path.exists(par_path):
                    os.makedirs(par_path)

                with open(data["path"], "w", encoding="utf-8") as file:
                    file.write(data["data"])
            case 'write':
                dir = os.path.dirname(data['path'])
                if not os.path.exists(dir):
                    os.makedirs(dir)
                flag = 'w'
                encoding = "utf-8"
                if 'flag' in data:
                    flag = data['flag']
                if 'encoding' in data:
                    encoding = data['encoding']

                with open(data["path"], flag, encoding=encoding) as file:
                    file.write(data["data"])
            case 'read':
                if os.path.exists(data['path']):
                    with open(data['path'], 'r', encoding='utf-8') as file:
                        sendmsg = file.read()
                else:
                    sendmsg = '文件不存在'
                    code = 404
            case "api":
                match data["query"]:
                    case "baidu":
                        sendmsg = {
                            "aud": {
                                "uk": baidu_aud("uk", data["data"]),
                                "en": baidu_aud("en", data["data"]),
                            },
                            "mean": baidu_translate(data["data"]),
                        }
            case "md_preview":
                # 如果不存在
                if not os.path.exists(mdEditor_path):
                    return json.dumps({"msg": "`typora`不存在", "code": 100})
                uid = uuid.uuid1()
                if not os.path.exists(temp_path):
                    os.makedirs(temp_path)
                # 临时文件路径
                temp_file = f"{temp_path}/{uid}_preview_TEMP_.md"
                with open(temp_file, "w", encoding="utf-8") as file:
                    file.write(data["data"])

                # 设置只读
                os.chmod(temp_file, 0o444)

                cmd = f'"{mdEditor_path}" "{temp_file}"'
                process = subprocess.Popen(cmd, shell=True)

                process.wait()

                sendmsg = {
                    # typora退出码
                    "code": process.returncode,
                    # 执行的命令
                    "cmd": cmd,
                }

                # 设置允许读写
                os.chmod(temp_file, 0o777)

                os.remove(temp_file)

            case "md_edit":
                # 如果不存在
                if not os.path.exists(mdEditor_path):
                    return json.dumps({"msg": "`typora`不存在", "code": 100})

                uid = uuid.uuid1()
                if not os.path.exists(temp_path):
                    os.makedirs(temp_path)

                # 临时文件路径
                temp_file = f"{temp_path}/{data['word']}_{uid}_TEMP_.md"

                with open(temp_file, "w", encoding="utf-8") as file:
                    file.write(data["data"])

                # os.system('start ' + f'"{mdEditor_path}" "{temp_file}"')
                # os.system(f'"{mdEditor_path}" "{temp_file}"')

                cmd = f'"{mdEditor_path}" "{temp_file}"'
                process = subprocess.Popen(cmd, shell=True)

                process.wait()

                with open(temp_file, "r", encoding="utf-8") as file:
                    # sendmsg = file.read()
                    sendmsg = {
                        # 编辑的文本内容
                        "content": file.read(),
                        # typora退出码
                        "code": process.returncode,
                        # 执行的命令
                        "cmd": cmd,
                    }

                if not data["leave_temp"]:
                    os.remove(temp_file)
            case "typora_path":
                sendmsg = mdEditor_path
            case "md_temp_path":
                sendmsg = temp_path
            case "del_md_temp":
                for root, dirs, files in os.walk(temp_path):
                    for file in files:
                        if file.endswith("_TEMP_.md"):
                            os.remove(os.path.join(root, file))
            case "alter_typora_path":
                mdEditor_path = data["path"]
                temp_path = os.path.dirname(mdEditor_path) + "/temp"

                config["typora_path"] = mdEditor_path

                sendmsg = [mdEditor_path, temp_path]

            case "convert":
                def convert(target='pdf'):
                    mdc_p = os.path.abspath(
                        os.path.join(config["dir_root"], "mdc/mdc.exe")
                    )
                    engine_p = os.path.abspath(
                        os.path.join(
                            config["dir_root"], f"wkhtmltopdf/wkhtmlto{target}.exe"
                        )
                    )
                    
                    #                     
                    if not os.path.exists(data['input']):
                        uid = uuid.uuid1()
                        if not os.path.exists(temp_path):
                            os.makedirs(temp_path)

                        # 临时文件路径
                        temp_file = f"{temp_path}/{uid}_convert_TEMP_.md"
                        with open(temp_file, "w", encoding="utf-8") as file:
                            file.write(data["input"])
                        data['input'] = temp_file
                    # 

                    cmd = f'"{mdc_p}" "{data['input']}" "{os.path.abspath(data['export_path'])}" "{engine_p}'
                    process = subprocess.Popen(cmd, shell=True)

                    process.wait()
                    
                    os.remove(data['input'])

                    return {
                        "mdc_p": mdc_p,
                        "engine_p": engine_p,
                        "cmd": cmd,
                        "code": process.returncode,
                    }
                match data["target"]:
                    case "pdf":
                        sendmsg = convert()
                    case "img":
                        sendmsg = convert('image')
                        pass
            case _:
                sendmsg = "unknown request"
                code = 1
    except:
        sendmsg = "不合法的数据"
        code = -1

    return json.dumps({"msg": sendmsg, "code": code})
